package com.heba.greenmulu.scan;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.product.ItemProductKeyWordObject;
import com.heba.config.CommonConfig;
import com.heba.database.model.KeyWord;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.DensityUtils;
import com.heba.view.ClearEditTextView;
import com.heba.view.FlowLayout;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

/**
 * 產品搜索
 * Created by jason on 2020/1/8.
 */
public class ItemProductSearchActivity extends BaseActivity {

    private ClearEditTextView clearEditTextView;
    private ImageView iv_right;
    private TextView tv_right;
    private TextView tv_random;
    private FlowLayout fl_view;
    private ImageView iv_trash;
    private RecyclerView rv_view;

    private QuickAdapter recycleAdapter;

    /**
     * 熱門關鍵詞
     */
    private List<ItemProductKeyWordObject> hotKeyWordList;

    /**
     * 搜索歷史
     */
    private List<KeyWord> historys;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_product_search);
        findViewById();
        initView();
        getKeyWordData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        queryKeywordData();
    }

    @Override
    protected void findViewById() {
        clearEditTextView = findViewById(R.id.clearEditText);
        iv_right = findViewById(R.id.img_right);
        tv_right = findViewById(R.id.txt_right);
        tv_random = findViewById(R.id.tv_random);
        fl_view = findViewById(R.id.fl_view);
        iv_trash = findViewById(R.id.iv_trash);
        rv_view = findViewById(R.id.rv_view);
    }

    @Override
    protected void initView() {

        iv_right.setVisibility(View.INVISIBLE);
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText(getResources().getString(R.string.cancel));

        tv_right.setOnClickListener(v -> finishActivity());

        hotKeyWordList = new ArrayList<>();

        historys = new ArrayList<>();

        recycleAdapter = new QuickAdapter<KeyWord>(historys) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_search_text_row;
            }

            @Override
            public void convert(VH holder, KeyWord data, int position) {
                holder.setText(R.id.tv_content, data.getKeyWordName());

                /**
                 * 搜索历史列表item监听
                 */
                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.PRODUCT_SEARCH_TITLE, data.getKeyWordName());
                    bundle.putString(CommonConfig.PRODUCT_KEYWORD, data.getKeyWordName());
                    openActivity(ItemProductSearchResultActivity.class, bundle);
                });
            }

        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        rv_view.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        rv_view.setAdapter(recycleAdapter);

        /**
         * 搜索關鍵詞
         */
        clearEditTextView.setOnEditTextListener(new ClearEditTextView.OnEditTextListener() {
            @Override
            public void onDeleteClick() {

            }

            @Override
            public void afterTextChanged(String text) {

            }

            @Override
            public void onSearchClick(String text) {
                //保存搜索關鍵詞到數據庫
                savaKeywords(text);

                //跳转
                Bundle bundle = new Bundle();
                bundle.putString(CommonConfig.PRODUCT_SEARCH_TITLE, text);
                bundle.putString(CommonConfig.PRODUCT_KEYWORD, text);
                openActivity(ItemProductSearchResultActivity.class, bundle);
            }

            @Override
            public void onIntent() {

            }
        });

        /**
         * 獲取隨機關鍵詞
         */
        tv_random.setOnClickListener(v -> getKeyWordData());

        /**
         * 刪除搜索歷史
         */
        iv_trash.setOnClickListener(v -> {
            historys.clear();
            LitePal.deleteAll(KeyWord.class);
            recycleAdapter.notifyDataSetChanged();
        });
    }

    /**
     * 更新流式佈局
     */
    private void updateHotKeyWordFlowView(List<ItemProductKeyWordObject> list) {
        fl_view.removeAllViews();

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(this, 30));
        params.rightMargin = DensityUtils.dip2px(this, 10);
        params.bottomMargin = DensityUtils.dip2px(this, 10);
        for (int i = 0; i < list.size(); i++) {
            fl_view.addView(updateFlowRowView(list.get(i)), params);
        }
    }

    /**
     * 添加item佈局
     */
    private View updateFlowRowView(ItemProductKeyWordObject object) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_search_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getKeywordName());

        /**
         * 传递热门关键词
         */
        tv_text.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.PRODUCT_SEARCH_TITLE, object.getKeywordName());
            bundle.putString(CommonConfig.PRODUCT_HOT_KEYWORD, object.getKeywordName());
            openActivity(ItemProductSearchResultActivity.class, bundle);
        });
        return view;
    }

    /**
     * 查詢搜索歷史
     */
    private void queryKeywordData() {
        historys.clear();
        List<KeyWord> keyWordList = LitePal.findAll(KeyWord.class);
        historys.addAll(keyWordList);
        recycleAdapter.notifyDataSetChanged();
    }

    /**
     * 保存搜索關鍵詞到數據庫中
     */
    private void savaKeywords(String name) {
        KeyWord object = new KeyWord();
        object.setKeyWordName(name);
        object.save();
    }

    /**
     * 獲取熱門關鍵詞數據
     */
    private void getKeyWordData() {
        loading.Start();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        client.get(Cfg.BaseUrl + "/Product/HotKeywords", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        loading.End();
                        hotKeyWordList.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemProductKeyWordObject> keyWordObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemProductKeyWordObject>>() {
                                }.getType());
                                hotKeyWordList.addAll(hotKeyWordList.size(), keyWordObjects);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 更新熱門關鍵詞view
                         */
                        updateHotKeyWordFlowView(hotKeyWordList);
                    }

                    public void Failure() {
                        super.Failure();
                        loading.End();
                    }

                });
    }

}
